<template>
	<view class="content">
		<view class="selfBox" style="margin-top: 60rpx;">
			<!-- 自行组织表单内容保持不变 -->
			<view class="inputItem">
				<text class="inputlabel">活动名称：</text>
				<input type="text" placeholder="请输入本次活动名称" class="input" v-model="title" />
			</view>
			<view class="inputItem">
				<text class="inputlabel">活动封面：(建议宽高比例为4:3)</text>
				<view class="imgItem" style="margin-top: 35rpx;" v-if="coverUrl">
					<image :src="coverUrl" class="uploadedImg" mode="aspectFill"></image>
					<view class="deleteBtn" @click.stop="deleteCover()">
						<view class="deleteX"></view>
					</view>
				</view>
				<view class="add" style="margin-top: 35rpx;" @click="chooseCover()" v-else>
					+
				</view>
			</view>
			<view class="inputItem">
				<text class="inputlabel">主办方：</text>
				<input type="text" placeholder="请输入活动主办方" class="input" v-model="sponsor" />
			</view>
			<view class="inputItem">
				<text class="inputlabel">活动规模（请输入数字）：</text>
				<input type="number" placeholder="请输入活动规模" class="input" v-model="num" @input="filterNumber('num')"
					inputmode="numeric" pattern="[0-9]*" />
			</view>
			<view class="inputItem">
				<text class="inputlabel">参与对象：</text>
				<picker mode='selector' @change="choosePerson" :value="personIndex" :range="personArray">
					<input type="text" placeholder="请选择" class="input" v-model="person" readonly
						style="pointer-events: none">
				</picker>
			</view>
			<view class="inputItem">
				<text class="inputlabel">活动预计金额（请输入数字）：</text>
				<input type="number" placeholder="请输入活动预计金额" class="input" v-model="money"
					@input="filterNumber('money')" inputmode="numeric" pattern="[0-9]*" />
			</view>
			<view class="inputItem">
				<text class="inputlabel">活动开始时间：</text>
				<uni-datetime-picker mode='datetime' @change="startTimeChange" return-type="timestamp">
					<input type="text" placeholder="请选择" class="input" v-model="start_time" readonly style="pointer-events: none">
				</uni-datetime-picker>
			</view>
			<view class="inputItem">
				<text class="inputlabel">活动结束时间：</text>
				<uni-datetime-picker mode='datetime' @change="endTimeChange" return-type="timestamp">
					<input type="text" placeholder="请选择" class="input" v-model="end_time" readonly style="pointer-events: none">
				</uni-datetime-picker>
			</view>
			<view class="inputItem">
				<text class="inputlabel">活动地点：</text>
				<input type="text" placeholder="请输入活动地点" class="input" v-model="address" />
			</view>
			<view class="inputItem">
				<text class="inputlabel">活动介绍：</text>
			</view>
			<textarea class="info" placeholder="请输入本次活动内容" maxlength="-1" v-model="into" />
			<view class="imgBox">
				<view class="imgItem" v-for="(img, index) in imgList" :key="index">
					<image :src="img" class="uploadedImg" mode="aspectFill"></image>
					<view class="deleteBtn" @click.stop="deleteImage(index)">
						<view class="deleteX"></view>
					</view>
				</view>
				<view class="add" @click="chooseImage()">+</view>
			</view>
			<view class="inputItem" style="margin-top: 60rpx;">
				<text class="inputlabel">发起形式：</text>
			</view>
			<view class="menuBox">
				<view class="menuItem" @click="changeMenu(0)">
					<image :src="baseurl + (menuIndex==0? 'associationAdd/5.png' : 'associationAdd/4.png')"
						class="agree"></image>
					<text class="menuLabel" :class="menuIndex==0?'menuActive':''">自行组织</text>
				</view>
				<view class="menuItem" @click="changeMenu(1)">
					<image :src="baseurl + (menuIndex==1? 'associationAdd/5.png' : 'associationAdd/4.png')"
						class="agree"></image>
					<text class="menuLabel" :class="menuIndex==1?'menuActive':''">需要帮助</text>
				</view>
			</view>
			<view class="helpBox" v-if="menuIndex==1">
				<view class="inputItem">
					<text class="inputlabel">01.我需要以下帮助（可多选）</text>
				</view>
				<!-- 循环渲染帮助选项 -->
				<view class="selItem" v-for="helpText in helpArr" :key="helpText" @click="toggleHelp(helpText)">
					<image
						:src="baseurl + (selectedHelp.includes(helpText) ? 'associationAdd/5.png' : 'associationAdd/4.png')"
						class="agree"></image>
					<text class="agreeText" :class="selectedHelp.includes(helpText) ? 'agreeActive' : ''">
						{{ helpText }}
					</text>
				</view>
				<view class="inputItem">
					<text class="inputlabel">02.联系方式</text>
				</view>
				<view style="display: flex;align-items: center;">
					<view class="selItem" v-for="(contactText,index) in contactArr" :key="index"
						@click="selectContact(index)">
						<image
							:src="baseurl + (selectedContact === index ? 'associationAdd/5.png' : 'associationAdd/4.png')"
							class="agree"></image>
						<text class="agreeText" :class="selectedContact === index ? 'agreeActive' : ''">
							{{ contactText }}
						</text>
					</view>
				</view>
				<!-- <view class="submit" @click="submit()">
					<text class="label">提交</text>
				</view> -->
			</view>
			<view class="submit" @click="submit()">
				<text class="label">发布</text>
			</view>
			<!-- 结果 -->
			<view class="resultBox" v-if="isResult">
				<view class="success" v-if="isSuccess">
					<image :src="baseurl+'associationAdd/25.png'" class="postSuccess"></image>
					<text class="result">发起成功</text>
					<text class="tips">活动发起成功，期待您的下次活动</text>
					<view class="btn" @click="$back(1)">
						确定
					</view>
				</view>
				<view class="success" v-if="isFail">
					<image :src="baseurl+'associationAdd/26.png'" class="postFail"></image>
					<text class="result">发起失败</text>
					<text class="tips">{{tips}}</text>
					<view class="btn" @click="again">
						再次发起
					</view>
				</view>
			</view>
		</view>
		<!-- 自己联系提交成功 -->
		<view class="resultBox" v-if="isSelfSuccess">
			<image :src="baseurl+'associationAdd/qrcode.png'" class="qrcode"></image>
			<text class="tips1">微信扫一扫，添加我们</text>
			<text class="tips2">或拨打</text>
			<text class="tips3" @click="$phone('15884637750')">15884637750</text>
			<view class="contactBtn" @click="$phone('15884637750')">
				<text class="label">立即联系</text>
			</view>
		</view>
		<!-- 结果 -->
		<view class="resultBox" v-if="isSubmit">
			<view class="success" v-if="isSubmitSuccess">
				<image :src="baseurl+'user/success.png'" class="postSuccess"></image>
				<text class="result">提交成功</text>
				<text class="tips">稍后会联系您，请注意接听来电！</text>
				<view class="btn" @click="$back(1)">
					确定
				</view>
			</view>
			<view class="success" v-if="isSubmitFail">
				<image :src="baseurl+'user/fail.png'" class="postFail"></image>
				<text class="result">提交失败</text>
				<text class="tips">{{tips}}</text>
				<view class="btn" @click="$back(1)">
					再次提交
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				baseurl: this.$baseurl,
				agreeUrl: 'associationAdd/4.png',
				imgList: [],
				urlList: [],
				title: '',
				content: '',
				id: '',
				isResult: false,
				isSuccess: false,
				isFail: false,
				menuIndex: -1,
				title: '',
				sponsor: '',
				date: '',
				coverUrl: '', // 活动封面（本地预览地址，最多1张）
				coverServerUrl: '', // 活动封面（服务器地址，用于提交）
				// 帮助和联系方式数组
				helpArr: ['社群空间预约', '方案设计协助', '活动推广协助', '活动经费申请', '活动费用报销'],
				contactArr: ['后台联系', '自己联系'],
				selectedHelp: [],
				selectedContact: -1,
				isSelfSuccess: false,
				isSubmit: false,
				isSubmitSuccess: false,
				isSubmitFail: false,
				start_time: '',
				start_time_stamp: '',
				end_time: '',
				end_time_stamp: '',
				address: '',
				into: '',
				attention: '',
				is_help: 0,
				personArray: ['所有人', '社群主理人', '社群成员'],
				personIndex: '',
				person: '',
				num: '',
				money: '',
				tips:'很遗憾提交失败，再次提交试试！'
			}
		},
		onLoad(options) {
			// 社群详情
			this.id = options.id;
		},
		methods: {
			filterNumber(field) {
				this[field] = this[field].replace(/[^0-9]/g, '');
			},
			choosePerson(e) {
				this.personIndex = e.detail.value;
				this.person = this.personArray[this.personIndex];
			},
			again() {
				this.isResult = false;
				this.isFail = false;
			},
			submit() {
				// 自行组织表单提交
				if (this.title == '') {
					this.$u.toast('请输入本次活动名称')
					return;
				}
				if (this.coverUrl == '') {
					this.$u.toast('请上传活动封面')
					return;
				}
				if (this.sponsor == '') {
					this.$u.toast('请输入活动主办方')
					return;
				}
				if (this.num === '' || /[^0-9]/.test(this.num) || this.num === '0') {
					this.$u.toast('请输入有效的活动规模（正整数）');
					return;
				}
				if (this.personIndex == '') {
					this.$u.toast('请选择参与对象')
					return;
				}
				if (this.money === '' || /[^0-9]/.test(this.money) || this.money === '0') {
					this.$u.toast('请输入有效的活动预计金额（正整数）');
					return;
				}
				if (this.start_time == '') {
					this.$u.toast('请选择活动开始时间')
					return;
				}
				if (this.end_time == '') {
					this.$u.toast('请选择活动结束时间')
					return;
				}
				if (this.into == '') {
					this.$u.toast('请输入本次活动内容')
					return;
				}
				// if (this.attention == '') {
				// 	this.$u.toast('请输入本次活动须知')
				// 	return;
				// }
				if (this.menuIndex == -1) {
					this.$u.toast('请选择发起形式')
					return;
				}
				if (this.selectedContact != -1) { //需要帮助
					this.is_help = 1;
				}
				this.$request.post('CommunityActivity/create_activity', {
					name: this.title,
					cover: this.coverServerUrl,
					sponsor: this.sponsor,
					start_time: this.start_time_stamp,
					end_time: this.end_time_stamp,
					address: this.address,
					into: this.into,
					activity_img: JSON.stringify(this.urlList),
					attention: '活动申请无须知',
					is_help: this.is_help,
					help_option: JSON.stringify(this.selectedHelp),
					is_relation: this.selectedContact,
					community_id: this.id,
					num: this.num,
					condition: this.personIndex,
					money: this.money,
					type: 2
				}).then(res => {
					if (res.data.code == 1) {
						if (this.is_help == 0) { //不需要帮助
							this.isSuccess = true;
							this.isResult = true;
						} else {
							if (this.selectedContact === 1) { //自己联系
								this.isSelfSuccess = true;
							} else {
								this.isSubmitSuccess = true;
								this.isSubmit = true;
							}
						}
					} else { //发布失败
						this.isResult = true;
						this.isFail = true;
						this.tips=res.data.msg;
					}
				})
			},
			startTimeChange(e) {
				this.start_time_stamp = Math.floor(e / 1000);
				this.start_time = this.formatTimeStampToReadable(e);
			},
			endTimeChange(e) {
				this.end_time_stamp = Math.floor(e / 1000);
				this.end_time = this.formatTimeStampToReadable(e);
			},
			changeMenu(index) {
				this.menuIndex = index;
			},
			formatTimeStampToReadable(timestamp) {
				const date = new Date(timestamp); // 时间戳是毫秒级，直接传入
				const year = date.getFullYear();
				const month = this.padZero(date.getMonth() + 1); // 月份0-11，需+1
				const day = this.padZero(date.getDate());
				const hour = this.padZero(date.getHours());
				const minute = this.padZero(date.getMinutes());
				return `${year}-${month}-${day} ${hour}:${minute}`;
			},
			// 新增：补零工具函数（确保月份/日期/时分是两位数）
			padZero(n) {
				return n < 10 ? `0${n}` : n;
			},
			// 选择活动封面（最多1张）
			chooseCover() {
				uni.chooseImage({
					count: 1, // 强制只能选1张
					sizeType: ["compressed"], // 压缩图片
					sourceType: ["album", "camera"], // 支持相册+相机
					success: (res) => {
						const tempFilePath = res.tempFilePaths[0]; // 仅取第一张
						this.coverUrl = tempFilePath; // 显示本地预览
						// 上传封面到服务器
						uni.uploadFile({
							url: `https://miantou.guguan.net/api/File/formImage`,
							header: {
								"Content-Type": "multipart/form-data",
								"token": JSON.parse(uni.getStorageSync('TOKEN')).value
							},
							filePath: tempFilePath,
							name: "file",
							fileType: "image",
							success: (res) => {
								try {
									const datas = JSON.parse(res.data);
									if (datas.code === 1 && datas.data?.uri) {
										this.coverServerUrl = datas.data.uri; // 保存服务器地址
									} else {
										this.coverUrl = ''; // 上传失败，清空预览
										this.$toast('封面上传失败：' + (datas.msg || '未知错误'));
									}
								} catch (e) {
									this.coverUrl = '';
									this.$toast('封面上传失败：返回格式错误');
								}
							},
							fail: () => {
								this.coverUrl = '';
								this.$toast('封面上传失败，请检查网络');
							}
						});
					}
				});
			},
			// 删除活动封面
			deleteCover() {
				this.coverUrl = ''; // 清空本地预览
				this.coverServerUrl = ''; // 清空服务器地址
			},
			//选择图片
			chooseImage() {
				uni.chooseImage({
					count: 1, //选择几张
					sizeType: ["compressed"], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ["album"], //从相册选择（也可以拍照
					success: (res) => {
						const tempFilePaths = res.tempFilePaths;
						const tempFiles = res.tempFiles;
						this.imgList.push(tempFilePaths[0]);
						uni.uploadFile({
							url: `https://miantou.guguan.net/api/File/formImage`,
							header: {
								"Content-Type": "multipart/form-data",
								"token": JSON.parse(uni.getStorageSync('TOKEN')).value
							},
							filePath: tempFilePaths[0],
							name: "file",
							fileType: "image",
							success: (res) => {
								console.log(res)
								const {
									data
								} = res
								let datas = JSON.parse(data)
								console.log(datas.data.uri)
								let temps = {
									url: datas.data.uri
								}
								this.urlList.push(datas.data.uri);
							},
							fail: (res) => {
								this.$toast('上传失败，请重新上传')
							}
						});
					}
				})
			},
			// 删除图片
			deleteImage(index) {
				this.imgList.splice(index, 1);
				this.urlList.splice(index, 1);
			},
			getValue(value) {
				this.content = value; // 接收子组件传递的值
			},

			// 帮助类型多选切换（直接操作文字）
			toggleHelp(text) {
				if (this.selectedHelp.includes(text)) {
					// 已选中：从数组中移除该文字
					this.selectedHelp = this.selectedHelp.filter(item => item !== text)
				} else {
					// 未选中：添加该文字到数组
					this.selectedHelp.push(text)
				}
			},
			// 联系方式单选切换（直接存储文字）
			selectContact(index) {
				this.selectedContact = index;
			}
		}
	}
</script>

<style lang="scss">
	.agree {
		width: 35rpx;
		height: 35rpx;
		margin-right: 30rpx;
	}

	/* 样式部分完全不变 */
	.contactBtn {
		width: 250rpx;
		height: 90rpx;
		background: #4E97AD;
		border-radius: 15rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 100rpx;
		margin-bottom: 150rpx;
		margin-left: 250rpx;
		border-radius: 45rpx;

		.label {
			font-size: 28rpx;
			color: #fff;
		}
	}

	.tips3 {
		width: 100%;
		text-align: center;
		font-size: 48rpx;
		font-weight: 400;
		margin-top: 35rpx;
		display: inline-block;
	}

	.tips2 {
		width: 100%;
		text-align: center;
		font-size: 24rpx;
		font-weight: 500;
		margin-top: 35rpx;
		display: inline-block;
	}

	.tips1 {
		width: 100%;
		text-align: center;
		font-size: 28rpx;
		font-weight: 500;
		margin-top: 60rpx;
		display: inline-block;
	}

	.qrcode {
		width: 280rpx;
		height: 280rpx;
		margin-left: 235rpx;
		margin-top: 150rpx;
	}

	.helpBox {
		width: 680rpx;
		padding-top: 75rpx;
		background-color: #fff;
		margin-top: 60rpx;
		margin-left: 35rpx;
		border-radius: 15rpx;

		.selItem {
			margin-left: 100rpx;
			margin-bottom: 40rpx;
			display: flex;
			align-items: center;
			cursor: pointer;

			.agreeActive {
				color: #000 !important;
				font-weight: 700 !important;
			}

			.agreeText {
				font-size: 28rpx;
				font-weight: 500;
				color: #919191;
			}


		}
	}

	.inputItem {
		position: relative;
		width: 670rpx;
		margin-left: 40rpx;
		margin-bottom: 40rpx;

		.inputlabel {
			font-size: 28rpx;
			font-weight: 500;
		}

		.input {
			width: 615rpx;
			height: 80rpx;
			background-color: #fff;
			border-radius: 15rpx;
			margin-top: 35rpx;
			padding-left: 55rpx;
		}
	}

	.menuActive {
		color: #4E97AD;
	}

	.menuBox {
		width: 100%;
		height: 100rpx;
		display: flex;
		align-items: center;
		margin-bottom: 55rpx;

		.menuItem {
			position: relative;
			width: 49%;
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;

			.menuLabel {
				font-size: 28rpx;
				font-weight: 700;
			}

			.menuLabelLine {
				width: 50rpx;
				height: 5rpx;
				background-color: #4E97AD;
				margin-top: 25rpx;
				position: absolute;
				bottom: 0;
				left: 158rpx;
			}
		}

		.menuLine {
			width: 2rpx;
			height: 40rpx;
			background-color: #919191;
		}
	}

	.resultBox {
		position: fixed;
		z-index: 100;
		top: 0;
		left: 0;
		width: 100%;
		height: 100vh;
		background-color: #FAFAFA;
		overflow-y: scroll;

		.btn {
			width: 252rpx;
			height: 94rpx;
			line-height: 94rpx;
			text-align: center;
			background-color: #4E97AD;
			border-radius: 47rpx;
			color: #fff;
			margin: 0 auto;
			margin-top: 90rpx;
			font-size: 28rpx;
			font-weight: 500;
		}

		.tips {
			width: 100%;
			text-align: center;
			font-size: 24rpx;
			font-weight: 500;
			margin-top: 35rpx;
			color: #919191;
			display: block;
		}

		.result {
			width: 100%;
			text-align: center;
			font-size: 36rpx;
			font-weight: 700;
			margin-top: 70rpx;
			display: block;

		}

		.postFail {
			width: 152rpx;
			height: 152rpx;
			margin-left: 306rpx;
			margin-top: 414rpx;
		}

		.postSuccess {
			width: 152rpx;
			height: 152rpx;
			margin-left: 306rpx;
			margin-top: 414rpx;
		}
	}

	.imgBox {
		width: 670rpx;
		margin: 50rpx 0 0 40rpx;
		display: flex;
		flex-wrap: wrap;
		gap: 15rpx;
	}

	.imgItem {
		position: relative;
		width: 154rpx;
		height: 154rpx;
		border-radius: 20rpx;
		background-color: #fff;
	}

	.uploadedImg {
		width: 100%;
		height: 100%;
	}

	.deleteBtn {
		position: absolute;
		top: -15rpx;
		right: -15rpx;
		width: 36rpx;
		height: 36rpx;
		border-radius: 50%;
		background-color: #D95945;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 10;
		touch-action: none;
	}

	.deleteX {
		width: 18rpx;
		height: 18rpx;
		position: relative;

		&::before {
			content: '';
			position: absolute;
			top: 50%;
			left: 0;
			width: 100%;
			height: 2rpx;
			background-color: #fff; // 白色线条
			transform: rotate(45deg) translateY(-50%);
		}

		&::after {
			content: '';
			position: absolute;
			top: 50%;
			left: 0;
			width: 100%;
			height: 2rpx;
			background-color: #fff; // 白色线条
			transform: rotate(-45deg) translateY(-50%);
		}
	}

	.add {
		width: 154rpx;
		height: 154rpx;
		border-radius: 20rpx;
		background-color: #fff;
		font-size: 60rpx;
		color: #cccccc;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.info {
		margin-left: 35rpx;
		margin-top: 20rpx;
		width: 610rpx;
		height: 600rpx;
		padding: 35rpx;
		border-radius: 15rpx;
		font-size: 28rpx;
		background-color: #fff;
	}


	.title {
		width: 645rpx;
		height: 90rpx;
		border-radius: 15rpx;
		margin-left: 35rpx;
		margin-top: 30rpx;
		background-color: #fff;
		padding-left: 35rpx;
	}

	.headBg {
		width: 100%;
		height: 180rpx;
	}

	.pyh-nv-box {
		position: absolute !important;
	}

	.content {
		width: 100%;
		background-color: #EDF6FA;
		display: flex;
		flex-direction: column;
		overflow-y: scroll;

		.submit {
			width: 490rpx;
			height: 90rpx;
			background: #4E97AD;
			border-radius: 15rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-top: 100rpx;
			margin-bottom: 150rpx;
			margin-left: 130rpx;
			border-radius: 45rpx;

			.label {
				font-size: 28rpx;
				color: #fff;
			}
		}
	}
</style>